package main

import (
	"errors"
	"fmt"
	"io"
	"net"
)

func handleRequest(conn net.Conn) {
	fmt.Printf("accept a new connection!\n")
	for {
		len, err := io.Copy(conn, conn)
		if err != nil {
			fmt.Printf("failed to copy :%s\n", err)
			break
		}
		if len == 0 {
			fmt.Printf("connection closed!\n")
			break
		}

		addr := conn.RemoteAddr().(*net.TCPAddr)
		ip := addr.IP.To4()
		fmt.Printf("[%d.%d.%d.%d] relay successfully,length:%d\n", ip[0], ip[1], ip[2], ip[3], len)
	}
}

func StartServer(bindAddr string) error {
	l, err := net.Listen("tcp", bindAddr)
	if err != nil {
		return errors.New(fmt.Sprintf("failed to connect server (%s), error(%s)\n", bindAddr, err))
	}

	defer l.Close()

	fmt.Printf("now listening on (%s)\n", bindAddr)

	for {
		conn, err := l.Accept()
		if err != nil {
			fmt.Printf("failed to accept the new connection: %s\n", err)
		}

		go handleRequest(conn)
	}

	return nil
}

func main() {
	if err := StartServer("0.0.0.0:4399"); err != nil {
		fmt.Printf("failed to start server:%s\n", err)
	}
}
